package com.ewhale.feitengguest.ui.shop.mine

import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.dto.ArticleDetailDto
import com.ewhale.feitengguest.presenter.shop.mine.ShopRechargePresenter
import com.ewhale.feitengguest.ui.WebViewActivity
import com.ewhale.feitengguest.utils.pay.*
import com.ewhale.feitengguest.view.shop.mine.ShopRechargeView
import com.simga.library.activity.MBaseActivity
import com.simga.library.http.JsonUtil
import com.simga.library.utils.LogUtil
import com.tencent.mm.sdk.openapi.IWXAPI
import com.tencent.mm.sdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.activity_shop_recharge.btn_commit
import kotlinx.android.synthetic.main.activity_shop_recharge.et_inputAmount
import kotlinx.android.synthetic.main.activity_shop_recharge.radioGroup
import kotlinx.android.synthetic.main.activity_shop_recharge.tv_2
import java.math.BigDecimal

class ShopRechargeActivity : MBaseActivity<ShopRechargePresenter>(), ShopRechargeView, PayCallBack, WeiXinPayCallBack {
    override fun withSuccess() {}
    override fun getViewId(): Int {
        return R.layout.activity_shop_recharge
    }

    override fun isUseBaseTitleBar(): Boolean {
        return true
    }
    private var payType = 2 //2支付宝1微信
    private var payUtils: PayUtils? = null
    private var api: IWXAPI? = null
    private var receiver: WeiXinPayReceiver? = null


    override fun init(savedInstanceState: Bundle?) {
        setTitle("支付")

        //第三方支付配置
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID)
        payUtils = PayUtils(this, this)
        receiver = WeiXinPayReceiver()
        receiver!!.setWeiXinPayCallBack(this)
        val filter = IntentFilter()
        filter.addAction(WeiXinPayReceiver.WEI_XI_PAY_CALLBACK)
        registerReceiver(receiver, filter)
    }

    override fun initListener() {
        super.initListener()
        tv_2.setOnClickListener {
            presenter.loadArticleDetails(14)
        }
        radioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rb_alipay -> {
                    payType = 2
                }
                R.id.rb_wechat -> {
                    payType = 1
                }
            }
        }
        btn_commit.setOnClickListener {
            val amount = et_inputAmount.text.toString()
            if (amount.isEmpty()) {
                showToast("请输入充值金额")
                return@setOnClickListener
            }
            if (amount.toBigDecimal().compareTo(BigDecimal(0)) == 0) {
                showToast("充值金额不能必须大于0")
                return@setOnClickListener
            }
            if (payType == 1) {
                if (!isWXAppInstalledAndSupported()) {
                    showToast("您未安装微信")
                    return@setOnClickListener
                }
            }
            presenter.walletRecharge(payType,amount.toBigDecimal())
        }
    }

    override fun showDetail(result: ArticleDetailDto) {
        WebViewActivity.open(mContext, "充值协议", result.content)
    }

    override fun goToThirdPay(info: Any) {
        if(payType == 1){
            val weixinDto = JsonUtil.fromJson(info.toString(),PayWeixinDto::class.java)
            payUtils!!.payByWXPay(weixinDto)
        }else{
            payUtils!!.payByAliPay(info.toString())
        }
    }
    override fun onPaySuccess(payType: PayType?) {
        showToast("支付成功")
        finishResult()
    }

    override fun onPayFail(payType: PayType?) {
        showToast("支付失败")
    }

    override fun onPayCancel(payType: PayType?) {
        showToast("支付取消")
    }

    override fun onWXPay(code: String?) {
        PayCallBackEvent(PayType.WXPAY, code).payAction(this)
    }

    /**
     * 判断是否已经安装微信
     *
     * @return (true.已安装 false.未安装)
     */
    private fun isWXAppInstalledAndSupported(): Boolean {
        val msgApi = WXAPIFactory.createWXAPI(this, null)
        msgApi.registerApp(Constants.APP_ID)
        return msgApi.isWXAppInstalled && msgApi.isWXAppSupportAPI
    }

    override fun onDestroy() {
        super.onDestroy()
        if (receiver != null) {
            unregisterReceiver(receiver)
        }
    }

    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String?, message: String?) {
        showErrorMsg(code, message)
    }

    companion object {
        fun open(mContext: MBaseActivity<*>) {
            mContext.startForResult(null,10001, ShopRechargeActivity::class.java)
        }
    }
}
